#include<iostream>
#include<string>
#include<mysql/mysql.h>


#define host "127.0.0.1" 
#define user "root"
#define pwd ""
#define dbname "gobang" 
#define port 3306

int main()
{
  //1.初始化Mysql句柄  
  MYSQL *mysql = mysql_init(NULL); //传NULL重新创建对象 
  if(mysql == NULL)
  {
    // 句柄初始化失败 
    std::cout << " mysql_init failed" << std::endl ;
    return -1;
  }

  //2.连接服务器 
  //mysql_real_connect(mysql,host,user,pwd,dbname,port,unix_socket,flag)
  if(mysql_real_connect(mysql,host,user,pwd,dbname,port,NULL,0) == NULL) 
  {
    // 连接服务器失败
    std::cout << " mysql_real_connect failed" << std::endl ;
    return -1;
  }

  //3.设置客户端字符集
  if(mysql_set_character_set(mysql,"utf8") != 0)
  {
    std::cout << " mysql_set_character_set failed" << std::endl ;
    return -1;
  }

  //4.选择要操作的数据库，在2中已经选择过了  
  

  //5.执行sql语句 
//  const char* sql = "insert student values(null,'张三',18,60,70.5,90.5);";
  //const char* sql = "delete from student where sid=2;";
 // const char* sql = "update student set ch=ch+30 where sid=1;";
  const char* sql = "select * from student;";
  int ret = mysql_query(mysql,sql);
  if(ret!=0)
  {
    //sql语句执行失败
    std::cout << sql << std::endl ;
    std::cout << "mysql_query faild :" << mysql_errno(mysql) << std::endl ;
    mysql_close(mysql); //关闭连接
    return -1;
  }
  
  //如果是查询语句，需要把查询结果保存到本地结果集 
  MYSQL_RES* res = mysql_store_result(mysql); //在堆中开了块空间
  if(res == nullptr)
  {
    mysql_close(mysql);
    return -1;
  }
  
  //获取结果集中的数据
  int num_row = mysql_num_rows(res); //获取查询的行数 
  int num_col = mysql_num_fields(res); //获取查询列数 

  //遍历每一行
  for(int i = 0;i < num_row; i++)
  {
      //获取当前行的查询结果，下次查询会自动查询下一次结果
      MYSQL_ROW row = mysql_fetch_row(res);
      //遍历每一列
      for(int j = 0 ; j < num_col ; j++)
      {
        std::cout << row[j] << '\t';
      }
      std::cout<< std::endl;
  }
  return 0;
}
